package com.shop.front.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.common.config.GlobalConfig;
import com.shop.common.entity.Banner;
import com.shop.common.entity.SearchRecord;
import com.shop.common.entity.system.SystemConfig;
import com.shop.common.mapper.SearchRecordMapper;
import com.shop.common.mapper.system.SystemConfigMapper;
import com.shop.common.util.OSSUtil;
import com.shop.common.util.UrlUtils;
import com.shop.front.service.IIndexService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页服务实现类
 */
@Service
public class IndexServiceImpl implements IIndexService {

    @Resource
    SearchRecordMapper searchRecordMapper;

    @Resource
    SystemConfigMapper systemConfigMapper;


    /**
     * 配置
     *
     * @author fzr
     * @return Map<String, Object>
     */
    @Override
    public Map<String, Object> config() {
        Map<String, Object> response = new LinkedHashMap<>();

        // 获取网站配置
        QueryWrapper<SystemConfig> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.select("type", "name", "value");
        configQueryWrapper.eq("type", "website");
        List<SystemConfig> websiteConfigs = systemConfigMapper.selectList(configQueryWrapper);
        for(SystemConfig websiteConfig : websiteConfigs) {
            List<Banner> banners = JSON.parseArray(websiteConfig.getValue(), Banner.class);
            banners.stream().forEach(item -> {
                item.setImage(OSSUtil.completeUrl(item.getImage()));
            });
            response.put(websiteConfig.getName(), banners);
        }

        // 响应数据
        response.put("version", GlobalConfig.version);
        response.put("domain", UrlUtils.domain());
        return response;
    }

    /**
     * 热搜
     *
     * @author fzr
     * @return List<String>
     */
    @Override
    public List<String> hotSearch() {
        List<String> list = new ArrayList<>();

        // 从搜索记录里按照关键词分组查询热搜词
        List<SearchRecord> searchRecords = searchRecordMapper.selectList(
                new QueryWrapper<SearchRecord>()
                        .select("keyword", "sum(count) as cnt")
                        .groupBy("keyword")
                        .orderByDesc("cnt")
                        .last("limit 10"));
        searchRecords.forEach(item -> list.add(item.getKeyword()));
        return list;
    }

    /**
     * 生成OSS上传文件的预签名URL
     *
     */
    @Override
    public Map<String, String> preUpload(String type) {
        return OSSUtil.preUpload(type);
    }

}
